﻿package com.controller;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import com.entity.Owner;
import com.entity.Page;
import com.entity.Uploadfile;
import com.entity.User;
import com.service.OwnerService;
import com.service.UploadService;
import com.service.UserService;
import com.util.DataUtil;
@Controller
@RequestMapping("/pc")
public class PC_UploadController {
	
	//log4j日志
	Logger logger=Logger.getLogger(PC_UploadController.class);
	
	@Resource
	UploadService uploadService;
	@Resource
	OwnerService ownerService;
	@Resource
	UserService userService;
	
	DataUtil dataUtil=new DataUtil();	//获取当前时间
	public String yaddress;				//小区地址名称
	public int yid;						//用户标示符
	public String getphone;				//手机号码
	private String url = "/home/apache-tomcat-7.0.47/webapps/image/pc"; //存储图片地址
	
	/**
	 * 添加注册信息
	 * @param file
	 * @param request
	 * @param upload
	 * @return
	 */
	@RequestMapping(value="/uploadfile",produces="text/html;charset=UTF-8")
	public String uploadfile(@RequestParam(value = "filepath", required = false) CommonsMultipartFile[] file, HttpServletRequest request,Uploadfile upload,ModelMap modelMap){
		logger.info("进入pc端添加信息");
		//查询手机号码
		Map<String,Object> maps=new HashMap<String,Object>();
		maps.put("yphone", upload.getYphone());
		Owner owners=ownerService.selectPhone(maps);
		if(owners!=null){
			//强制类型转换
			int Intynumber=owners.getYnumber();
			String Stringynumber=Integer.toString(Intynumber);
			//获取每个file名称
			String fileName=file[0].getOriginalFilename();
			String fileName1=file[1].getOriginalFilename();
			String fileName2=file[2].getOriginalFilename();
			//截取每个file.后面的后缀名
			String str=fileName.substring(fileName.indexOf("."));
	        String str1=fileName1.substring(fileName1.indexOf("."));
	        String str2=fileName2.substring(fileName2.indexOf("."));
	        //判断上传图片后缀名
	        String jpg=".jpg",png=".png",jpeg=".jpeg",gif=".gif";
	        if(str.equals(jpg) || str.equals(png) || str.equals(jpeg) || str.equals(gif)){
		        String newfileName=dataUtil.data()+"01"+str;
		        File targetFile = new File(url, newfileName);  
			    if(!targetFile.exists()){  
			         targetFile.mkdirs();  
			    }  
				    try {  
				         file[0].transferTo(targetFile); 
				    }catch (Exception e) {  
				         e.printStackTrace();  
				    }
		    if(str1.equals(jpg) || str1.equals(png) || str1.equals(jpeg) || str1.equals(gif)){
			    String newfileName1=dataUtil.data()+"02"+str;
			    File targetFile1 = new File(url, newfileName1);  
				if(!targetFile1.exists()){  
				    targetFile1.mkdirs();  
				}  
					try {  
					     file[1].transferTo(targetFile1); 
					}catch(Exception e) {  
					     e.printStackTrace();  
					}
			if(str2.equals(jpg) || str2.equals(png) || str2.equals(jpeg) || str2.equals(gif)){
				 String newfileName2=dataUtil.data()+"03"+str;
				 File targetFile2 = new File(url, newfileName2);  
				if(!targetFile2.exists()){  
					 targetFile2.mkdirs();  
				}  
					try {  
						 file[2].transferTo(targetFile2); 
					} catch (Exception e) {  
						 e.printStackTrace();  
					}
        	upload.setYfilename("https://wwl.ycws.cc/image/pc/"+newfileName);
            upload.setYfilename1("https://wwl.ycws.cc/image/pc/"+newfileName1);
	        upload.setYfilename2("https://wwl.ycws.cc/image/pc/"+newfileName2);
        	upload.setYname(upload.getYname());
        	upload.setYsex(upload.getYsex());
        	upload.setYowner("业主");
        	upload.setYphone(upload.getYphone());
        	upload.setYaddress(yaddress);
        	upload.setYdetailed(upload.getYdetailed());
        	upload.setYindex("0");
        	upload.setYnumber(Stringynumber);
        	upload.setCreatetime(dataUtil.data1());
        	upload.setUpdatetime(dataUtil.data1());
			uploadService.add(upload);
			logger.info("pc端添加用户,数据上传...");
			System.out.println("---手机号码---"+getphone);
			//return "redirect:/pc/selectByPage?result=1&id="+yid+"&pageCurrent="+0;
			return "redirect:/pc/selectPhone?pageCurrent=0&phone="+getphone;
			}
		}
	}  
		}else{
			//添加手机号码
			maps.put("ynumber", null);
			maps.put("yphone", upload.getYphone());
			maps.put("openid", "pc");
			ownerService.insertPhone(maps);
			//查询手机号码
			Owner owner=ownerService.selectPhoneString(upload.getYphone());
			int a=owner.getYnumber();
			String number=Integer.toString(a);
			//获取每个file名称
			String fileName=file[0].getOriginalFilename();
			String fileName1=file[1].getOriginalFilename();
			String fileName2=file[2].getOriginalFilename();
			//截取每个file.后面的后缀名
			String str=fileName.substring(fileName.indexOf("."));
	        String str1=fileName1.substring(fileName1.indexOf("."));
	        String str2=fileName2.substring(fileName2.indexOf("."));
	        //判断上传图片后缀名
	        String jpg=".jpg",png=".png",jpeg=".jpeg",gif=".gif";
	        if(str.equals(jpg) || str.equals(png) || str.equals(jpeg) || str.equals(gif)){
		        String newfileName=dataUtil.data()+"01"+str;
		        File targetFile = new File(url, newfileName);  
		        if(!targetFile.exists()){  
		            targetFile.mkdirs();  
		        }  
			        try {  
			            file[0].transferTo(targetFile); 
			        } catch (Exception e) {  
			            e.printStackTrace();  
			        }
		    if(str1.equals(jpg) || str1.equals(png) || str1.equals(jpeg) || str1.equals(gif)){
	        	String newfileName1=dataUtil.data()+"02"+str1;
		        File targetFile1 = new File(url, newfileName1);  
		        if(!targetFile1.exists()){  
		            targetFile1.mkdirs();  
		        }  
			        try {  
			            file[1].transferTo(targetFile1); 
			        } catch (Exception e) {  
			            e.printStackTrace();  
			        }
		    if(str2.equals(jpg) || str2.equals(png) || str2.equals(jpeg) || str2.equals(gif)){
	        	String newfileName2=dataUtil.data()+"03"+str2;
		        File targetFile2 = new File(url, newfileName2);  
		        if(!targetFile2.exists()){  
		            targetFile2.mkdirs();  
		        }  
			        try {  
			            file[2].transferTo(targetFile2); 
			        } catch (Exception e) {  
			            e.printStackTrace();  
			        }
			        logger.info("pc端添加一个业主,同时添加用户,数据上传中...");
	        	upload.setYfilename("https://wwl.ycws.cc/image/upload/"+newfileName);
	            upload.setYfilename1("https://wwl.ycws.cc/image/upload/"+newfileName1);
		        upload.setYfilename2("https://wwl.ycws.cc/image/upload/"+newfileName2);
	        	upload.setYname(upload.getYname());
	        	upload.setYsex(upload.getYsex());
	        	upload.setYowner("业主");
	        	upload.setYphone(upload.getYphone());
	        	upload.setYaddress(yaddress);
	        	upload.setYdetailed(upload.getYdetailed());
	        	upload.setYindex("0");	//默认未支付
	        	upload.setYnumber(number);
	        	upload.setCreatetime(dataUtil.data1());
	        	upload.setUpdatetime(dataUtil.data1());
				uploadService.add(upload);
				}
		     }
	     }
	}
		//return "redirect:/pc/selectPhone?result=1&id="+yid+"&pageCurrent="+0;
		return "redirect:/pc/selectPhone?pageCurrent=0&phone="+getphone;
	}
	/**
	 * 分页查询
	 * result是登录的结果:1为登录成功
	 * id是:小区分配的账户
	 * pageCurrent是:当前显示的页数
	 */
	@RequestMapping("/selectByPage")
	public String selectByPage(int result,int id,int pageCurrent,ModelMap map){
		logger.info("----selectByPage----");
		map.addAttribute("result", result);
		User user=userService.getById(id);
		yaddress=user.getYaddress();
		yid=user.getYid();
		map.addAttribute("username", yaddress);
		map.addAttribute("userid", yid);
		List<Uploadfile> uploadfiles=uploadService.getAddress(user.getYaddress());	//模糊查询,显示所有相同小区地址信息
		Page page=new Page();
		Map<String,Object> maps=new HashMap<String,Object>();
		maps.put("yaddress", yaddress);
		maps.put("startpage",pageCurrent*page.getPageSize());	//当前页*每页显示的数量
		maps.put("stoppage", page.getPageSize());
		List<Uploadfile> uploadfilePageList=uploadService.selectByPage(maps);
		int total=uploadfiles.size();
		int pageTotal=total%page.getPageSize()==0?total/page.getPageSize():total/page.getPageSize()+1;
		map.addAttribute("uploadfiles", uploadfilePageList);
		map.addAttribute("pageTotal", pageTotal);
		map.addAttribute("pageCurrent", pageCurrent+1);
		return "showAll";
	}
	/**
	 * 根据姓名或者手机和小区地址查询用户信息,后分页
	 * @throws UnsupportedEncodingException 
	 * @throws Exception 
	 */
	@RequestMapping("/selectYnameOrYphone")
	public String selectYnameOrYphone(HttpServletRequest request,int pageCurrent,ModelMap map) throws UnsupportedEncodingException{
		String Sname=request.getParameter("name").toString();
		String name=java.net.URLDecoder.decode(Sname,"UTF-8");	//设置乱码
		String phone=request.getParameter("phone");
		if(name == "" && phone == ""){
			System.out.println("----1----");
			System.out.println("name-----"+name+"\t phone-----"+phone);
			return "redirect:/pc/selectByPage?result=1&id="+yid+"&pageCurrent=0"; 
		}else{
			System.out.println("----2----");
			System.out.println("-----pageCurrent----"+pageCurrent);
			System.out.println("name-----"+name+"\t phone-----"+phone);
			map.addAttribute("name", name);
			map.addAttribute("phone", phone);
			map.addAttribute("result", 1);
			Page page=new Page();
			Map<String,Object> maps=new HashMap<String,Object>();
			maps.put("yname", name);
			maps.put("yphone", phone);
			List<Uploadfile> uploadfiles=uploadService.selectYnameOrYphone(maps);
			Map<String,Object> maps1=new HashMap<String,Object>();
			maps1.put("yname", name);
			maps1.put("yphone", phone);
			maps1.put("startpage", pageCurrent*page.getPageSize());
			maps1.put("stoppage", page.getPageSize());
			maps1.put("yaddress", yaddress);
			List<Uploadfile> uploadfilesList=uploadService.selectYnameYphoneByPage(maps1);
			int total=uploadfiles.size();
			int pageTotal =total%page.getPageSize()==0?total/page.getPageSize():total/page.getPageSize()+1;
			map.addAttribute("uploadfiles", uploadfilesList);
			map.addAttribute("pageTotal", pageTotal);
			map.addAttribute("pageCurrent", pageCurrent+1);
			return "selectYnameOrYphone";
		}
	}
	/**
	 * 查询手机号码,分页
	 */
	@RequestMapping("/selectPhone")
	public String selectPhone(HttpServletRequest request,int pageCurrent,ModelMap map){
		System.out.println("pageCurrent"+pageCurrent);
		int result=1;
		map.addAttribute("result", result);
		map.addAttribute("userid", yid);
		getphone=request.getParameter("phone");
		map.addAttribute("phone", getphone);
		Map<String,Object> maps=new HashMap<String,Object>();
		maps.put("yphone", getphone);
		Owner owner=ownerService.selectPhone(maps);
		if(owner!=null){
			System.out.println(owner.getYnumber());
			Map<String,Object> maps0=new HashMap<String,Object>();
			maps0.put("ynumber", owner.getYnumber());
			maps0.put("yaddress", yaddress);
			List<Uploadfile> uploadfiles=uploadService.selectYnumberAndAddress(maps0);
			Page page=new Page();
			Map<String,Object> maps1=new HashMap<String,Object>();
			maps1.put("ynumber", owner.getYnumber());
			maps1.put("startpage", pageCurrent*page.getPageSize());
			maps1.put("stoppage", page.getPageSize());
			maps1.put("yaddress", yaddress);
			List<Uploadfile> uploadfileList=uploadService.selectYnumberByPage(maps1);
			int total=uploadfiles.size();
			int pageTotal=total%page.getPageSize()==0?total/page.getPageSize():total/page.getPageSize()+1;
			map.addAttribute("uploadfiles", uploadfileList);
			map.addAttribute("pageTotal", pageTotal);
			map.addAttribute("pageCurrent", pageCurrent+1);
			return "newShowAll";
		}else{
			return "newShowAll";
		}
	}
	
	@RequestMapping("/get_id")
	public String get_id(int id,ModelMap map){
		Uploadfile upload=uploadService.select(id);
		map.addAttribute("uploads", upload);
		return "update";
	} 
	@RequestMapping("/newget_id")
	public String newget_id(int id,ModelMap map){
		Uploadfile upload=uploadService.select(id);
		map.addAttribute("uploads", upload);
		return "newupdate";
	} 

	@RequestMapping("/delete_id")
	public String delete_id(int id){
		uploadService.delete(id);
		return "redirect:/pc/selectByPage?result=1&id="+yid+"&pageCurrent="+0;
	}
	
	@RequestMapping("/newdelete_id")
	public String newdelete_id(int id){
		uploadService.delete(id);
		return "redirect:/pc/selectPhone?pageCurrent=0&phone="+getphone;
	}
	
	@RequestMapping("/update_id")
	public String update_id(Uploadfile uploadfile){
		Date updatedata=new Date();
        SimpleDateFormat updatedateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updatenewData = updatedateFormat.format(updatedata); 
        uploadfile.setUpdatetime(updatenewData);
		uploadService.update(uploadfile);
		return "redirect:/pc/selectByPage?result=1&id="+yid+"&pageCurrent="+0;
	}
	
	@RequestMapping("/newupdate_id")
	public String newupdate_id(Uploadfile uploadfile){
		Date updatedata=new Date();
        SimpleDateFormat updatedateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updatenewData = updatedateFormat.format(updatedata); 
        uploadfile.setUpdatetime(updatenewData);
		uploadService.update(uploadfile);
		return "redirect:/pc/selectPhone?pageCurrent=0&phone="+getphone;
	}
	
	//详情页
	@RequestMapping("/details")
	public String details(int id,ModelMap map){
		Uploadfile upload=uploadService.select(id);
		map.addAttribute("uploads", upload);
		return "details";
	} 
}
